package com.ixion.mongo.utils;

import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

import com.mongodb.MongoClient;

public class Connector extends MongoClient {
	/**
	 * mongo的单例获取key
	 */
	public static final String CLIENT_KEY = "IXION_MONGO_CLIENT_CONNECTION_KEY";
	/**
	 * 存放单例的map
	 */
	private static Map<String, Connector> map = new HashMap<String, Connector>();

	/**
	 * 私有化构造方法
	 * 
	 * @throws UnknownHostException
	 */
	private Connector() throws UnknownHostException {
		super();
	}

	/**
	 * 私有化构造方法
	 * 
	 * @throws UnknownHostException
	 */
	private Connector(String host, int port) throws UnknownHostException {
		super(host, port);
	}

	/**
	 * 实例化Mongo连接,公共静态实例化方法
	 * 
	 * @return 一个mongo链接
	 */
	public static Connector instants() {
		if (map.get(CLIENT_KEY) == null) {
			try {
				map.put(CLIENT_KEY, new Connector());
			} catch (UnknownHostException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		return map.get(CLIENT_KEY);
	}

	/**
	 * 获取一个mongo连接
	 * 
	 * @param host
	 *            主机
	 * @param port
	 *            端口
	 * @return mongo客户端连接
	 */
	public static Connector instants(String host, int port) {
		// map无值或者map中的连接的host或者是port和传入参数不一致都重新创建一个
		if (map.get(CLIENT_KEY) == null || ((Connector) map.get(CLIENT_KEY)).getAddress().getHost() != host || ((Connector) map.get(CLIENT_KEY)).getAddress().getPort() != port) {
			try {
				// 创建之前先关闭之前的连接
				if (map.get(CLIENT_KEY) != null) {
					((Connector) map.get(CLIENT_KEY)).close();
				}
				// 用新的连接覆盖之前的
				map.put(CLIENT_KEY, new Connector(host, port));
			} catch (UnknownHostException e) {
				e.printStackTrace();
				throw new RuntimeException(e);
			}
		}
		return map.get(CLIENT_KEY);
	}
}
